/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aptech.util;

import com.aptech.business.AccountManager;
import com.aptech.business.BaseManager;
import com.aptech.domain.JPA.Account;
import com.aptech.business.IAccountManager;
import com.aptech.domain.model.AccountDO;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

/**
 *
 * @author Admin
 */
public class AptechUtility extends BaseManager {
    private static Logger logger = Logger.getLogger(AptechUtility.class);
    public static User getPrincipal(HttpSession session) {
    // Do nothing with the session because Spring give us a better way to retrieve the principal
      return (User) ((SecurityContext)
        SecurityContextHolder.getContext()).getAuthentication().getPrincipal();
    }
    public static AccountDO getWebUserDetails() {
        AccountDO account = null;
        try {
            IAccountManager accountManager = new AccountManager();
            Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            User user = null;
            if (obj != null && obj instanceof User) {
                user = (User) obj;
                account = accountManager.getAccountByUsername(user.getUsername());
            }
        } catch (Exception e) {
            logger.debug("getWebUserDetails");
        }
        return account;
    }
    public static boolean isAnonymous() {        
        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx != null) {
            Authentication auth = ctx.getAuthentication();
            return resolver.isAnonymous(auth);
        }
        return true;
    }
    public static String getCurLoginUsername() {        
       return getWebUserDetails().getUsername();
    }
    public static int getCurLoginId() {        
       return getWebUserDetails().getAccountId();
    }
    

}
